package block

import (
	"bytes"
	"errors"
	"github.com/boltdb/bolt"
)

/**
 *@author:zhengyilong
 *@email:1797344574@qq.com
 *@phone:13479394730
 *@DateTime:2022/4/17 19:31
 **/

type ChainIterator struct {
	DB *bolt.DB
	CurrentHash []byte
}

func (interator *ChainIterator) Next() (*Block, error) {
	var block *Block
	var err error
	err = interator.DB.View(func(tx *bolt.Tx) error {
		bk := tx.Bucket([]byte(BUCKET_BLOCK))
		if bk == nil {
			return errors.New("没有桶")
		}

		blockBytes := bk.Get(interator.CurrentHash)

		block, err = DeSerialize(blockBytes)
		if err != nil {
			return errors.New("反序列化失败")
		}

		interator.CurrentHash = block.PrevHash

		return nil
	})

	return block,err
}

func (iterator *ChainIterator) HashNext() bool {
	int := bytes.Compare(iterator.CurrentHash, nil)
	return int != 0
}